Popular Searches
Popular Course Categories
Popular Courses

XPath with Attributes

XPath with Attributes

XPath in Selenium

XPath with Attributes in Selenium

XPath with Attributes is a powerful technique used in Selenium WebDriver to locate web elements by using their HTML attributes. Attributes such as id, name, class, type, value, href, placeholder, title, role, and custom attributes can be combined with XPath to create targeted element locators.

XPath is included among the locator strategies covered in Selenium training at JustAcademy, along with CSS selectors and other WebElement-location techniques. JustAcademy Selenium Training Course

You can also visit the Selenium Course Demo Registration page for course-demo information.


1. What is XPath with Attributes?

XPath with Attributes is an XPath expression that identifies an HTML element by checking one or more attributes of that element.

The basic syntax is:

//tagname[@attribute='value']

For example:

//input[@id='username']

This XPath searches for an input element whose id attribute has the value username.


2. What is an HTML Attribute?

An HTML attribute provides additional information about an HTML element. Attributes are normally written inside the opening tag.

Example:

<input id="username" name="user" type="text" placeholder="Enter Username">

In this example, the element contains several attributes:

AttributeValuePurpose
idusernameUniquely identifies the element when designed to be unique
nameuserProvides a name for the element
typetextDefines the input type
placeholderEnter UsernameDisplays hint text inside the input


3. Basic XPath Attribute Syntax

The most common syntax for XPath with an attribute is:

//tagname[@attribute='value']

Example:

//input[@id='username']

Here:

  • // searches for matching elements in the document.
  • input represents the HTML tag.
  • @id represents the id attribute.
  • 'username' represents the expected attribute value.


4. XPath with ID Attribute

The id attribute is commonly used to construct XPath expressions.

HTML:

<input id="username" type="text">

XPath:

//input[@id='username']

Selenium:

driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");

This expression locates an input element whose id is username.


5. XPath with Name Attribute

The name attribute can also be used to identify an element.

HTML:

<input name="username" type="text">

XPath:

//input[@name='username']

Selenium:

driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");


6. XPath with Class Attribute

The class attribute can be used to locate elements based on their CSS class value.

HTML:

<input class="login-input" type="text">

XPath:

//input[@class='login-input']

Selenium:

driver.findElement(By.xpath("//input[@class='login-input']")).sendKeys("admin");

Exact class matching should be used carefully because an element can contain multiple class names.


7. XPath with Type Attribute

The type attribute is useful for identifying specific types of input elements.

HTML:

<input type="email" id="email">

XPath:

//input[@type='email']

A more specific XPath can be:

//input[@type='email' and @id='email']


8. XPath with Value Attribute

The value attribute can be used when the element contains a useful value.

HTML:

<input type="submit" value="Login">

XPath:

//input[@value='Login']

Selenium:

driver.findElement(By.xpath("//input[@value='Login']")).click();


9. XPath with Placeholder Attribute

The placeholder attribute is frequently used with input fields.

HTML:

<input type="text" placeholder="Enter Username">

XPath:

//input[@placeholder='Enter Username']

Selenium:

driver.findElement(By.xpath("//input[@placeholder='Enter Username']")).sendKeys("admin");


10. XPath with Title Attribute

The title attribute can provide additional information about an element and can also be used in XPath.

HTML:

<button title="Login to Application">Login</button>

XPath:

//button[@title='Login to Application']


11. XPath with Href Attribute

The href attribute is commonly used for locating links.

HTML:

<a href="/home">Home</a>

XPath:

//a[@href='/home']

Selenium:

driver.findElement(By.xpath("//a[@href='/home']")).click();


12. XPath with Multiple Attributes

Multiple attributes can be combined when one attribute is not sufficient to identify an element.

HTML:

<input id="username" name="user" type="text">

XPath:

//input[@id='username' and @name='user']

Another example:

//input[@type='text' and @name='user']

Multiple attributes can make an XPath more specific when several elements share the same tag or individual attribute values.


13. XPath with AND Operator

The and operator is used when all specified attribute conditions must be satisfied.

//input[@type='text' and @name='username']

This expression requires both conditions to be true.

Another example:

//button[@id='loginBtn' and @type='submit']


14. XPath with OR Operator

The or operator is used when either condition can match the required element.

//input[@id='username' or @name='username']

This XPath can match an input where either the id or name attribute has the value username.


15. XPath with Multiple Attribute Conditions

Several attributes can be combined to create a more precise locator.

HTML:

<input id="username" name="user" type="text" placeholder="Enter Username">

XPath:

//input[@id='username' and @name='user' and @type='text']

Another example:

//input[@name='user' and @placeholder='Enter Username']


16. XPath with Partial Attribute Value

Sometimes the complete attribute value is not stable. In such cases, the contains() function can be used.

HTML:

<input id="username_12345" type="text">

XPath:

//input[contains(@id,'username')]

This XPath searches for an input whose id contains the text username.


17. XPath with contains() and Attribute

The contains() function is useful when only part of an attribute value is known or stable.

Syntax:

//tagname[contains(@attribute,'partial-value')]

Example:

//button[contains(@id,'login')]

This can match a button whose id contains login.


18. XPath with starts-with() and Attribute

The starts-with() function identifies elements where an attribute value begins with a specified string.

HTML:

<input id="username_12345" type="text">

XPath:

//input[starts-with(@id,'username')]

This can be useful when an application generates dynamic IDs with a predictable prefix.


19. XPath with Attribute and Text

Attributes can be combined with visible text to create a more specific locator.

HTML:

<button id="loginBtn">Login</button>

XPath:

//button[@id='loginBtn' and text()='Login']

Another example:

//button[@type='submit' and contains(text(),'Login')]


20. XPath with Attribute and normalize-space()

When visible text contains additional whitespace, normalize-space() can be combined with an attribute condition.

//button[@id='loginBtn' and normalize-space()='Login']

This can help when whitespace around the visible text affects an exact text comparison.


21. XPath for Login Username Field

Consider the following HTML:

<input id="username" name="username" type="text" placeholder="Enter Username">

Possible XPath expressions include:

//input[@id='username']

//input[@name='username']

//input[@placeholder='Enter Username']

//input[@type='text' and @name='username']

Selenium example:

driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");


22. XPath for Password Field

HTML:

<input id="password" name="password" type="password">

XPath:

//input[@id='password']

Using multiple attributes:

//input[@name='password' and @type='password']

Selenium:

driver.findElement(By.xpath("//input[@name='password' and @type='password']")).sendKeys("admin123");


23. XPath for Login Button

HTML:

<button id="loginBtn" type="submit">Login</button>

XPath using ID:

//button[@id='loginBtn']

XPath using type:

//button[@type='submit']

XPath using multiple attributes:

//button[@id='loginBtn' and @type='submit']

XPath using text and attribute:

//button[@id='loginBtn' and text()='Login']


24. XPath for Checkbox Using Attributes

HTML:

<input id="terms" type="checkbox" name="terms">

XPath:

//input[@id='terms']

Using multiple attributes:

//input[@type='checkbox' and @name='terms']

Selenium:

driver.findElement(By.xpath("//input[@type='checkbox' and @name='terms']")).click();


25. XPath for Radio Button Using Attributes

HTML:

<input type="radio" name="gender" value="male">

<input type="radio" name="gender" value="female">

XPath for the male radio button:

//input[@type='radio' and @value='male']

XPath for the female radio button:

//input[@type='radio' and @value='female']


26. XPath for Dropdown Using Attributes

HTML:

<select id="country" name="country">

    <option value="india">India</option>

    <option value="usa">USA</option>

</select>

XPath for the select element:

//select[@id='country']

XPath for the India option:

//select[@id='country']/option[@value='india']

XPath using text:

//select[@id='country']/option[text()='India']


27. XPath for Links Using Attributes

HTML:

<a href="/products" id="productsLink">Products</a>

Using href:

//a[@href='/products']

Using ID:

//a[@id='productsLink']

Using both attributes:

//a[@id='productsLink' and @href='/products']


28. XPath with Class Attribute and Multiple Classes

An HTML element can contain multiple class names.

Example:

<button class="btn btn-primary login-button">Login</button>

An exact class match would be:

//button[@class='btn btn-primary login-button']

However, if the class list can change, contains() can be used:

//button[contains(@class,'login-button')]

Another approach is to use a class-token pattern:

//button[contains(concat(' ',normalize-space(@class),' '),' login-button ')]


29. XPath for Dynamic ID Attributes

Modern web applications may generate IDs dynamically.

Example:

<input id="user_12345" type="text">

Another page load might produce:

<input id="user_67890" type="text">

Instead of depending on the changing number, use a stable part:

//input[contains(@id,'user_')]

If the stable prefix is known, starts-with() can also be used:

//input[starts-with(@id,'user_')]


30. XPath for Dynamic Class Attributes

Dynamic applications can also generate changing class values.

Example:

<button class="btn-login-123">Login</button>

XPath:

//button[contains(@class,'btn-login')]

The expression focuses on the stable portion of the class value.


31. XPath with Attribute Existence

XPath can check whether an element contains a particular attribute.

For example:

//input[@required]

This selects input elements that have the required attribute.

Another example:

//button[@disabled]

This selects buttons that have the disabled attribute.


32. XPath Using not() with Attributes

The not() function can be used to exclude elements with a particular attribute or condition.

Example:

//input[not(@disabled)]

This identifies input elements that do not have the disabled attribute.

Another example:

//button[not(@type='button')]

This excludes buttons whose type attribute is button.


33. XPath Using Attribute Values with Special Characters

When an attribute value contains special characters or quotation marks, the XPath expression must be constructed carefully.

Simple value:

//input[@placeholder='Enter Username']

For complex string values, XPath string functions or appropriate quoting techniques may be required.


34. XPath with Attribute and Parent Relationship

An attribute-based XPath can be combined with parent navigation.

HTML:

<div class="login-form">

    <input id="username">

</div>

XPath:

//input[@id='username']/parent::div

This locates the div parent of the input identified using its id attribute.


35. XPath with Attribute and Child Relationship

An attribute condition can identify a parent and then navigate to its child element.

HTML:

<div id="loginForm">

    <input name="username">

    <input name="password">

</div>

Username:

//div[@id='loginForm']/input[@name='username']

Password:

//div[@id='loginForm']/input[@name='password']


36. XPath with Attribute and Descendant Relationship

The descendant relationship can be used when the target element may be located at different nesting levels.

//form[@id='loginForm']//input[@name='username']

The double slash after the form allows the XPath to search for matching input descendants at different levels inside the form.


37. XPath with Attribute and Parent-Child Structure

Combining attributes with DOM relationships can create targeted locators.

Example:

//div[@id='loginForm']//button[@type='submit']

This searches for a submit button inside the element whose id is loginForm.


38. XPath with Attribute and Following-Sibling

Attributes can identify one element, and following-sibling can locate a related element.

HTML:

<label for="username">Username</label>

<input id="username" type="text">

XPath:

//label[@for='username']/following-sibling::input[@id='username']


39. XPath with Attribute and Preceding-Sibling

The preceding-sibling axis can locate an element appearing before another element.

//input[@id='username']/preceding-sibling::label

A more specific version can be:

//input[@id='username']/preceding-sibling::label[@for='username']


40. XPath with Attribute and Ancestor

The ancestor axis can locate a higher-level element using an attribute condition.

//input[@id='username']/ancestor::form[@id='loginForm']

This searches for the loginForm ancestor of the username input.


41. XPath with Attribute and Descendant

The descendant axis can be explicitly used with attributes.

//form[@id='loginForm']/descendant::input[@type='text']

This identifies text input elements inside the form.


42. XPath for Tables Using Attributes

Attributes are useful when working with tables containing unique IDs.

HTML:

<table id="employees">

    <tr>

        <td>John</td>

        <td>QA Tester</td>

    </tr>

</table>

Table:

//table[@id='employees']

First row:

//table[@id='employees']//tr[1]

First cell:

//table[@id='employees']//tr[1]/td[1]


43. XPath for Specific Table Row Using Attributes and Text

Suppose the table contains:

<table id="employees">

    <tr>

        <td>101</td>

        <td>John</td>

        <td>QA Tester</td>

    </tr>

</table>

The row can be located using:

//table[@id='employees']//tr[td[text()='John']]

The role cell can then be located using:

//table[@id='employees']//tr[td[text()='John']]/td[3]


44. XPath with Data Attributes

Modern web applications often use custom data attributes such as data-testid, data-id, data-role, or data-name.

HTML:

<button data-testid="login-button">Login</button>

XPath:

//button[@data-testid='login-button']

Another example:

//div[@data-role='login-form']

Custom attributes can be useful when they are stable and intentionally provided for automation or testing.


45. XPath with aria-label Attribute

Accessibility-related attributes such as aria-label can sometimes provide meaningful locator values.

HTML:

<button aria-label="Search">Search</button>

XPath:

//button[@aria-label='Search']

This can locate the button using its aria-label attribute.


46. XPath with Role Attribute

The role attribute can also be used when it is present and provides a stable value.

HTML:

<button role="button" id="submitBtn">Submit</button>

XPath:

//button[@role='button' and @id='submitBtn']


47. XPath with Multiple Custom Attributes

Multiple custom attributes can be combined just like standard HTML attributes.

//button[@data-testid='login-button' and @aria-label='Login']

This requires both attribute conditions to match.


48. XPath Attribute Value Containing Dynamic Text

When part of an attribute is stable and another part changes, contains() can be used.

Example:

<button id="submit-order-12345">Submit</button>

XPath:

//button[contains(@id,'submit-order')]

This avoids depending on the changing numeric portion.


49. XPath Attribute Value Starting with Stable Text

starts-with() is useful when the beginning of the attribute remains consistent.

//button[starts-with(@id,'submit-order')]

This identifies buttons whose id begins with submit-order.


50. XPath Attribute Value with Exact Match

An exact attribute match is used when the complete attribute value is known.

//input[@id='username']

Exact matching is simple and readable when the attribute value is stable.


51. XPath Attribute Value with Partial Match

A partial match is useful when the complete attribute value is not stable.

//input[contains(@id,'username')]

This can match elements whose id contains username.


52. XPath Attribute Comparison

XPath attribute conditions can be used to compare an element's attribute value with a required value.

ConditionExample
Exact Attribute//input[@id='username']
Contains Attribute//input[contains(@id,'user')]
Starts With//input[starts-with(@id,'user')]
Multiple Attributes//input[@id='username' and @type='text']
OR Conditions//input[@id='username' or @name='username']
Attribute Exists//input[@required]
Attribute Excluded//input[not(@disabled)]


53. XPath with Attributes in Selenium WebDriver

Selenium WebDriver uses By.xpath() to pass an XPath expression to findElement() or findElements().

WebElement username = driver.findElement(

    By.xpath("//input[@id='username']")

);

The returned WebElement can then be used for actions such as typing, clicking, reading text, or retrieving attributes.


54. XPath Attributes with sendKeys()

sendKeys() can enter text into an element located using an attribute-based XPath.

driver.findElement(

    By.xpath("//input[@name='username']")

).sendKeys("admin");


55. XPath Attributes with click()

click() can be used after locating buttons, links, checkboxes, radio buttons, and other clickable elements.

driver.findElement(

    By.xpath("//button[@id='loginBtn']")

).click();


56. XPath Attributes with getAttribute()

getAttribute() can retrieve an attribute value from a located WebElement.

String idValue = driver.findElement(

    By.xpath("//input[@name='username']")

).getAttribute("id");

System.out.println(idValue);


57. XPath Attributes with getText()

getText() retrieves visible text from an element located using an attribute-based XPath.

String buttonText = driver.findElement(

    By.xpath("//button[@id='loginBtn']")

).getText();

System.out.println(buttonText);


58. XPath Attributes with findElements()

findElements() can locate multiple elements matching an attribute-based XPath.

List<WebElement> textInputs = driver.findElements(

    By.xpath("//input[@type='text']")

);

System.out.println(textInputs.size());


59. XPath Attributes with Explicit Wait

Attribute-based XPath can be combined with explicit waits when elements are loaded dynamically.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[@id='loginBtn']")

    )

);

loginButton.click();


60. XPath Attributes in Page Object Model

Attribute-based XPath locators can be stored inside Page Object Model classes to keep locators organized.

public class LoginPage {

    private WebDriver driver;

    private By username =

        By.xpath("//input[@id='username']");

    private By password =

        By.xpath("//input[@id='password']");

    private By loginButton =

        By.xpath("//button[@id='loginBtn']");

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

    public void login(String user, String pass) {

        driver.findElement(username).sendKeys(user);

        driver.findElement(password).sendKeys(pass);

        driver.findElement(loginButton).click();

    }

}


61. XPath with Attributes in a Login Form

Consider the following login form:

<form id="loginForm">

    <input id="username" name="username" type="text">

    <input id="password" name="password" type="password">

    <button id="loginBtn" type="submit">Login</button>

</form>

Username:

//input[@id='username']

Password:

//input[@id='password']

Login button:

//button[@id='loginBtn']

Using the form as a context:

//form[@id='loginForm']//input[@name='username']


62. Complete Selenium Example Using XPath Attributes

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class XPathAttributesExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com/login");

        driver.findElement(

            By.xpath("//input[@id='username']")

        ).sendKeys("admin");

        driver.findElement(

            By.xpath("//input[@id='password']")

        ).sendKeys("admin123");

        driver.findElement(

            By.xpath("//button[@id='loginBtn']")

        ).click();

        driver.quit();

    }

}


63. XPath with Attributes vs ID Locator

FeatureXPath with AttributeID Locator
Selenium MethodBy.xpath()By.id()
Attribute SupportCan use many attributesUses the ID value
Text SupportCan combine attributes with textDoes not directly use text
Multiple ConditionsSupportedNot applicable in the same XPath-style expression
Functionscontains(), starts-with(), normalize-space(), etc.Not applicable
RelationshipsParent, child, sibling, ancestor, descendant, etc.Not applicable


64. XPath with Attributes vs CSS Selector

FeatureXPathCSS Selector
Attribute SelectionSupportedSupported
Text MatchingSupported through XPath functionsDoes not provide XPath-style text() matching
Parent NavigationSupportedDifferent capabilities depending on selector and browser support
Sibling NavigationSupportedSupported through CSS combinators
FunctionsContains, starts-with, normalize-space, etc.Uses CSS selector syntax and pseudo-classes
Selenium MethodBy.xpath()By.cssSelector()


65. Common Mistakes with XPath Attributes

  • Using the wrong attribute name.
  • Using an incorrect attribute value.
  • Forgetting the @ symbol before the attribute name.
  • Using incorrect quotation marks.
  • Assuming a class value is always unique.
  • Using unstable dynamic IDs as exact matches.
  • Creating an XPath that matches multiple elements.
  • Using unnecessary attributes in the locator.
  • Using indexes when a stable attribute is available.
  • Not validating the XPath before using it in automation.


66. How to Validate XPath with Attributes in Chrome

  1. Open the web application in Chrome.
  2. Right-click the required element.
  3. Select Inspect.
  4. Open the Console tab.
  5. Use the $x() function.
  6. Enter the XPath expression.
  7. Check the returned elements.
  8. Modify the XPath if it matches unintended elements.
  9. Use the validated XPath in Selenium.

Example:

$x("//input[@id='username']")

Multiple-attribute example:

$x("//input[@id='username' and @type='text']")

Contains example:

$x("//button[contains(@id,'login')]")


67. How to Check XPath Uniqueness

An attribute-based XPath should be checked to determine whether it identifies the intended element.

Example:

$x("//input[@id='username']")

If multiple elements are returned, the locator may need additional conditions.

For example:

//form[@id='loginForm']//input[@id='username']

Another approach is to combine attributes:

//input[@id='username' and @type='text']


68. Best Practices for XPath with Attributes

  • Prefer stable attributes whenever possible.
  • Use unique attributes when they are reliably unique.
  • Use multiple attributes when one attribute does not identify the element sufficiently.
  • Use contains() for stable portions of dynamic attributes.
  • Use starts-with() when a stable attribute prefix exists.
  • Avoid depending on dynamically generated values when a stable alternative is available.
  • Keep XPath expressions readable.
  • Avoid unnecessary DOM levels.
  • Use indexes only when required.
  • Validate XPath expressions in browser Developer Tools.
  • Use meaningful attributes when the application provides them.
  • Store important locators in Page Object Model classes.
  • Use explicit waits when elements are loaded dynamically.


69. Real-World XPath Attribute Automation Flow

Open Browser

↓

Open Web Application

↓

Inspect Web Element

↓

Identify Available Attributes

↓

Select Stable Attribute

↓

Create XPath Expression

↓

Add Multiple Conditions if Required

↓

Validate XPath in Browser

↓

Use By.xpath()

↓

Locate WebElement

↓

Perform Action

↓

Validate Result

↓

Continue Test Execution


70. XPath Attribute Quick Reference

PurposeExample
ID//input[@id='username']
Name//input[@name='username']
Class//input[@class='login-input']
Type//input[@type='text']
Value//input[@value='Login']
Placeholder//input[@placeholder='Enter Username']
Href//a[@href='/home']
Title//button[@title='Login']
Exact Attribute//input[@id='username']
Contains Attribute//input[contains(@id,'user')]
Starts With//input[starts-with(@id,'user')]
Multiple Attributes//input[@id='username' and @type='text']
OR Conditions//input[@id='username' or @name='username']
Attribute Exists//input[@required]
Exclude Attribute//input[not(@disabled)]
Data Attribute//button[@data-testid='login-button']
ARIA Attribute//button[@aria-label='Search']


71. Practical Exercise

Create a login page containing the following elements:

  • Username input with id and name attributes.
  • Password input with id and type attributes.
  • Remember Me checkbox with a data-testid attribute.
  • Login button with id and type attributes.
  • Forgot Password link with an href attribute.

Create XPath expressions using attributes for each element.

//input[@id='username']

//input[@id='password' and @type='password']

//input[@data-testid='remember-me']

//button[@id='loginBtn' and @type='submit']

//a[contains(@href,'forgot-password')]

Validate each XPath using:

$x("YOUR_XPATH")


72. XPath with Attributes Interview Questions

Q1. What is XPath with Attributes?

XPath with Attributes is an XPath technique used to locate web elements by matching their HTML attributes and attribute values.

Q2. What is the basic syntax?

//tagname[@attribute='value']

Q3. How do you locate an input using its ID?

//input[@id='username']

Q4. How do you use multiple attributes?

//input[@id='username' and @type='text']

Q5. How do you locate an element using a partial attribute value?

//input[contains(@id,'user')]

Q6. What is starts-with() used for?

starts-with() is used when the beginning portion of an attribute value is stable while the remaining portion may change.

Q7. Can XPath check whether an attribute exists?

Yes. An attribute can be checked directly.

//input[@required]

Q8. Can XPath exclude an attribute condition?

Yes. The not() function can be used.

//input[not(@disabled)]

Q9. Can multiple attributes be combined with AND?

Yes. The and operator can combine multiple attribute conditions.

Q10. Can OR be used with attributes?

Yes. The or operator can be used when either condition may identify the element.

Q11. How can XPath with attributes be tested in Chrome?

Use the browser Console and the $x() function to test the XPath expression.

Q12. Can attribute-based XPath handle dynamic elements?

Yes. Stable portions of dynamic attributes can be targeted using functions such as contains() and starts-with().


73. XPath with Attributes Learning Checklist

  • Understand HTML attributes.
  • Understand XPath attribute syntax.
  • Use ID attributes with XPath.
  • Use name attributes with XPath.
  • Use class attributes with XPath.
  • Use type attributes with XPath.
  • Use value attributes with XPath.
  • Use placeholder attributes with XPath.
  • Use href attributes with XPath.
  • Use title attributes with XPath.
  • Combine multiple attributes.
  • Use the and operator.
  • Use the or operator.
  • Use contains() with attributes.
  • Use starts-with() with attributes.
  • Check attribute existence.
  • Use not() with attributes.
  • Handle dynamic attribute values.
  • Use custom data attributes.
  • Use aria attributes when appropriate.
  • Combine attributes with DOM relationships.
  • Validate XPath expressions in Chrome.
  • Use XPath attributes with Selenium WebDriver.
  • Practice stable and maintainable locator creation.


74. Key Points to Remember

  • XPath can locate elements using HTML attributes.
  • The basic syntax is //tagname[@attribute='value'].
  • ID, name, class, type, value, href, title, placeholder, data attributes, and aria attributes can be used in XPath expressions.
  • Multiple attributes can be combined using and.
  • The or operator can be used when either condition can identify the element.
  • contains() is useful for partial attribute values.
  • starts-with() is useful for stable attribute prefixes.
  • Attributes can be combined with text and DOM relationships.
  • Dynamic attributes should be handled using stable portions of their values.
  • Attribute-based XPath should be validated before use in Selenium.
  • Stable and readable XPath expressions are easier to maintain.
  • Selenium WebDriver uses By.xpath() to work with XPath expressions.


75. Conclusion

XPath with Attributes is an important Selenium WebDriver technique for locating web elements using their HTML attributes. It allows testers to create targeted XPath expressions using attributes such as id, name, class, type, value, href, placeholder, title, data attributes, and accessibility-related attributes.

Attribute-based XPath can also be combined with multiple conditions, XPath functions such as contains() and starts-with(), visible text, parent-child relationships, sibling relationships, and other DOM navigation techniques. These capabilities make it possible to construct locators for both simple and complex web applications.

When working with dynamic applications, stable portions of attribute values can be targeted instead of relying on changing values. XPath expressions should also be validated in browser Developer Tools and kept as simple and readable as practical.

JustAcademy's Selenium training covers Selenium WebDriver, locators including XPath and CSS selectors, WebElements, browser automation, waits, dynamic elements, TestNG, Page Object Model, framework development, and practical automation projects. Explore JustAcademy Selenium Training.

For additional course information, visit the JustAcademy Selenium Course Demo Registration page.

whatsapp